package com.unitd.frame.springweb.upload.base;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @desc 上传文件的文件头信息
 * @filename UploadFileHeader.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/10
 */
public class UploadFileHeader {
	public UploadFileHeader() {
	}

	/**
	 * @desc 将读取到的上传字节码信息转换成字符串
	 * @param bytes 上传文件字节码信息
	 * @return
	 */
	public static String bytesToHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		if (null != bytes && bytes.length > 0) {
			for (int i = 0; i < bytes.length; ++i) {
				int v = bytes[i] & 255;
				String hv = Integer.toHexString(v);
				if (hv.length() < 2) {
					sb.append(0);
				}
				sb.append(hv);
			}

			return sb.toString();
		} else {
			return null;
		}
	}

	/**
	 * @desc 读取指定路径下的文件, 并将读取到的内容转换成字符串输出
	 * @param filePath 需要读取的文件路径
	 * @return String
	 */
	public static String getThreeBytes(String filePath) {
		FileInputStream is = null;
		String value;

		try {
			is = new FileInputStream(filePath);
			byte[] b = new byte[3];
			is.read(b, 0, b.length);
			value = bytesToHexString(b);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e.getMessage());
				}
			}
		}
		return value;
	}
}